/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dnstry;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.DocFlavor.STRING;
import javax.swing.JOptionPane;

/**
 *
 * @author Claudiu
 */
public class DnsQuery {
  /** Creates new form UdpClient */
    public DatagramPacket packet;
    public DatagramPacket packet2;
    public DatagramSocket socket;
    public DatagramSocket socket2;
    ArrayList <String> addressString;
    ArrayList <DnsEntry> entrys;
    
    public DnsQuery() {
      
        try {
            addressString = new ArrayList<String>();
            entrys = new ArrayList<DnsEntry>();
            //socket = new DatagramSocket(1500, InetAddress.getByName("127.0.0.1"));
            socket = new DatagramSocket(1500);
            socket.setSoTimeout(3000);
            System.out.println("online");
        } catch (Exception ex) {
            Logger.getLogger(UdpClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void nukeSocket(){
        try{
            socket.close();
        }catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
                try{
            socket2.close();
        }catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }

 
    byte[] formDNSReq(String name) {
        //  String name= "www.yahoo.com";
        int width = 12 + name.length() + 6;
        int id = 5744;

        DnsSendStream send = new DnsSendStream(name,false);
        byte[] headerMessage = send.getStream();
        return headerMessage;
    }
    public  String[] getIp(String address, String dnsServerAddress) throws Exception
    {
        String [] returnIp = new String[10];
        int answrCount=0;
        if(addressString.contains(address))
        {
            try{
                int i= addressString.indexOf(address);
                DnsEntry entry  = entrys.get(i);
            //    if( Calendar.SECOND < entry.getTtl())
            //    {
                    returnIp[answrCount]= entry.getIP();
                    answrCount++;
             //   }
                if(answrCount >0)
                return  returnIp;
            }catch(Exception e)
            {
                e.printStackTrace();
                  throw  new Exception("dns failure :"+" " +answrCount +" "+returnIp[0] +"   "+ addressString.indexOf(address)+ "  "+entrys.get(addressString.indexOf(address)) );
            }
        }//else{
        try {
            byte[] bytes = formDNSReq(address);
            packet = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(dnsServerAddress), 53);
            int len = bytes.length;
            socket.send(packet);
            packet2 = new DatagramPacket(new byte[512], 512);
            socket.receive(packet2);
            bytes = packet2.getData();
            System.out.println();

            DnsAnswer answer = new DnsAnswer(bytes, len);

            answer.parse();
                        int maxTTL=0;
            int maxIndex=0;
            for (int i = 0; i < answer.entryList.size(); i++) {
               // ShowText.append("\n parsed response : " + answer.entryList.get(i).toString());
                if(answer.entryList.get(i).getType() ==1)
                {
                    returnIp[answrCount] = answer.entryList.get(i).getIP();
                    if ( answer.entryList.get(i).getTtl() >= maxTTL )
                    {
                        maxTTL = answer.entryList.get(i).getTtl();
                        maxIndex = i;

                    }
                    answrCount++;

                }
            }
            if(answer.entryList.size()<1)
                            throw  new Exception("dns failure : "+address + "    "+ answer.getAdditionRecordsCount() +"  " +answer.getAnswerRecordCount() + "  "+ answer.getNameServerCount() +"  "+answer.entryList.size());
            else{
            addressString.add(address);
            answer.entryList.get(maxIndex).setTtl( answer.entryList.get(maxIndex).getTtl() +Calendar.SECOND);
            entrys.add(answer.entryList.get(maxIndex));
            }
        } catch (Exception ex) {
           // Logger.getLogger(UdpClient.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
            throw  ex;
        } return  returnIp;
     //       FileWriter fstream = new FileWriter("myFile.txt", true);
     //       BufferedWriter out = new BufferedWriter(fstream);

            //Close the output stream

       //     for (int i = 0; i < answer.entryList.size(); i++) {

       //         out.write("address : " + Message_field.getText() + " from : " + address_bar.getText() + " : " + answer.entryList.get(i).toString() + "\n");
       //         ShowText.append("\n --->" + answer.entryList.get(i).getIP());
       //         if (answer.entryList.get(i).getType() == 1) {
       //             out.write("ip: " + answer.entryList.get(i).getIP() + "\n");
       //         }
       //     }
      //      out.close();
       // }
  //      return  returnIp;

    }
    public InetAddress getIneAddress(String address, String dnsServerAddress) throws Exception
    {
        InetAddress address_return = null;
        String [] aux= new String[20];
        try {
             aux = getIp(address, dnsServerAddress);
            

             //   System.out.println("+++++++++++++++++++++++++++++++++++++++" + aux[0]);
                String var = aux[0];
                address_return = Inet4Address.getByName(var);
 
            return address_return;
        } catch (Exception ex) {
          //  Logger.getLogger(DnsQuery.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
            throw  new Exception("Dns Filure : address  "+address_return.toString() + " ** "+aux[0] + " address :"+address);
        }
    }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
//            // TODO add your handling code here:
//            //socket.connect(InetAddress.getLocalHost(),8888);
//            //           String text = Message_field.getText();
//           String[] ipList =  getIp(Message_field.getText(),address_bar.getText());
//            for ( int i = 0 ; i < ipList.length; i ++)
//            {
//                if( ipList[i] != null)
//                ShowText.append("\n------>"+ipList[i] );
//            }
//            byte[] bytes = formDNSReq(Message_field.getText());
//            packet = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(address_bar.getText()/*"81.180.223.1""4.2.2.2"*/), 53);
//            int len = bytes.length;
//
//            socket.send(packet);
////            System.out.println("objSet");
//            packet2 = new DatagramPacket(new byte[512], 512);
//            socket.receive(packet2);
//
//            bytes = packet2.getData();
//
//            System.out.println();
//            ShowText.append("recieved ");
//            ShowText.append("\n");
//            for (int i = 0; i < packet2.getLength(); i++) {
//                int aux = bytes[i];
//                //       Byte au_ = new Byte(aux);
//
//
//                int val = bytes[i] & 0x80;
//
//                val += bytes[i] & 0x7F;
//
//                System.out.print(" " + bytes[i] + " ");
//                if (aux > 'A' - 1) {
//                    ShowText.append(" " +/*bytes[i]*/ (char) (val)/*+":"+aux*/ + " ");
//                } else {
//                    ShowText.append(" " +/*bytes[i]*/ val/*+":"+aux*/ + " ");
//                }
//                if ((i % 8 == 0) && (i != 0)) {
//                    ShowText.append("\n");
//                }
//            }
//            System.out.println("len:" + len);
//            DnsAnswer answer = new DnsAnswer(bytes, len);
//            ShowText.append(" \n arCount:" + answer.getAnswerRecordCount());
//            ShowText.append(" \n nsCount:" + answer.getNameServerCount());
//            ShowText.append(" \n addCount:" + answer.getAdditionRecordsCount());
//            answer.parse();
//            for (int i = 0; i < answer.entryList.size(); i++) {
//                ShowText.append("\n parsed response : " + answer.entryList.get(i).toString());
//            }
//            FileWriter fstream = new FileWriter("myFile.txt", true);
//            BufferedWriter out = new BufferedWriter(fstream);
//
//            //Close the output stream
//
//            for (int i = 0; i < answer.entryList.size(); i++) {
//
//                out.write("address : " + Message_field.getText() + " from : " + address_bar.getText() + " : " + answer.entryList.get(i).toString() + "\n");
//                ShowText.append("\n --->" + answer.entryList.get(i).getIP());
//                if (answer.entryList.get(i).getType() == 1) {
//                    out.write("ip: " + answer.entryList.get(i).getIP() + "\n");
//                }
//            }
//            out.close();
        } catch (Exception ex) {
            Logger.getLogger(UdpClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }




}
